<!--
  文件名：LoginView.vue
  功能：用户登录页面
  作用：提供登录表单界面，处理用户登录逻辑
  模块关系：
    - 使用 Element Plus 表单组件
    - 调用 auth.js 的登录接口
    - 使用 Pinia authStore 保存登录信息
    - 登录成功后跳转到目标页面或首页
  作者：白永康
  学号：2501210209
-->
<script setup>
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { login, register } from '@/data/auth'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

// 表单模式：login 或 register
const mode = ref('login')
const loading = ref(false)

// 表单数据
const formData = reactive({
  username: '',
  password: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const formRef = ref(null)

/**
 * 处理登录
 */
async function handleLogin() {
  try {
    await formRef.value.validate()
    loading.value = true
    
    const result = await login(formData.username, formData.password)
    
    // 保存认证信息到 Pinia store 和 localStorage
    authStore.setAuth(result)
    
    ElMessage.success('登录成功')
    
    // 跳转到原来想访问的页面，或首页
    const redirect = route.query.redirect || '/apps'
    router.push(redirect)
    
  } catch (error) {
    ElMessage.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

/**
 * 处理注册
 */
async function handleRegister() {
  try {
    await formRef.value.validate()
    loading.value = true
    
    const result = await register(formData.username, formData.password)
    
    // 注册成功后自动登录
    authStore.setAuth(result)
    
    ElMessage.success('注册成功')
    
    // 跳转到首页
    router.push('/apps')
    
  } catch (error) {
    ElMessage.error(error.message || '注册失败')
  } finally {
    loading.value = false
  }
}

/**
 * 提交表单
 */
function handleSubmit() {
  if (mode.value === 'login') {
    handleLogin()
  } else {
    handleRegister()
  }
}

/**
 * 切换登录/注册模式
 */
function toggleMode() {
  mode.value = mode.value === 'login' ? 'register' : 'login'
  formData.confirmPassword = ''
  formRef.value?.clearValidate()
}
</script>

<template>
  <div class="login-container">
    <div class="login-card">
      <h1 class="title">{{ mode === 'login' ? '用户登录' : '用户注册' }}</h1>
      
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
        @submit.prevent="handleSubmit"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            show-password
            clearable
          />
        </el-form-item>
        
        <el-form-item
          v-if="mode === 'register'"
          label="确认密码"
          prop="confirmPassword"
        >
          <el-input
            v-model="formData.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
            clearable
          />
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            style="width: 100%"
          >
            {{ mode === 'login' ? '登录' : '注册' }}
          </el-button>
        </el-form-item>
        
        <div class="toggle-mode">
          <span v-if="mode === 'login'">
            还没有账号？
            <el-link type="primary" @click="toggleMode">立即注册</el-link>
          </span>
          <span v-else>
            已有账号？
            <el-link type="primary" @click="toggleMode">立即登录</el-link>
          </span>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-card {
  width: 420px;
  padding: 40px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 32px;
}

.toggle-mode {
  text-align: center;
  margin-top: 16px;
  font-size: 14px;
  color: #666;
}
</style>
